package com.zkingsoft.actions.client;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.shcm.bean.SendResultBean;
import com.shcm.send.DataApi;
import com.shcm.send.OpenApi;
import com.zkingsoft.actions.common.BaseController;
import com.zkingsoft.model.Dictionary;
import com.zkingsoft.model.Member;
import com.zkingsoft.model.UserBind;
import com.zkingsoft.model.Userdata;
import com.zkingsoft.plugin.util.StringUtils;
import com.zkingsoft.pojo.Result;
import com.zkingsoft.services.DictionaryService;
import com.zkingsoft.services.UserBindService;
import com.zkingsoft.services.UserdataService;

/**
 * @description 跨平台转账
 * @author 姜友瑶
 * @email 935090232@qq.com
 * @date 2016-06-26
 */
@Controller
@RequestMapping(value = "/transfer")
public class TransferController extends BaseController {
	private static final Logger log = Logger.getLogger(TransferController.class);
	private static String sOpenUrl = "http://smsapi.c123.cn/OpenPlatform/OpenApi";
	private static String sDataUrl = "http://smsapi.c123.cn/DataPlatform/DataApi";
	// 接口帐号
	private static final String account = "1001@501165190001";
	// 接口密钥
	private static final String authkey = "06E45CA85279896B9D828C946146A9CC";
	// 通道组编号
	private static final int cgid = 4940;
	// 默认使用的签名编号(未指定签名编号时传此值到服务器)
	private static final int csid = 101;
	
	@Resource 
	private DictionaryService dictionaryService;
	@Resource 
	private UserdataService userDataService;
	@Resource
	private UserBindService userBindService;
	
	private String code = "";//验证码
	private Dictionary dict;
	
	/**
	 * 转账登录页面
	 * @return
	 */
	@RequestMapping(value = "/toTransfer")
	public String toTransfer(){
		List<Dictionary> list = null;
		Userdata userData = (Userdata)getSession().getAttribute("gameUser");
		if(userData!=null){
			UserBind userBind =  userBindService.findByGameId(userData.getUserid());
			if(userBind==null){//未绑定
				list = dictionaryService.findByModel(null);
			}else{//已绑定
				list = new ArrayList<Dictionary>();
				Dictionary dictionary = dictionaryService.findById(userBind.getDictId());
				list.add(dictionary);
				getRequest().setAttribute("bindTel", userBind.getTel());
			}
		}
		if(list!=null&&list.size()>0){
			getRequest().setAttribute("list", list);
		}
		return "client/transfer-login";
	}
	
	/**
	 * 转账提交页面
	 * @return
	 */
	@RequestMapping(value = "/toTransferApply")
	public String toTransferApply(){
		log.info("进入转账提交页面。。。");
		Member member = (Member)getSession().getAttribute("member");
		Userdata userData = (Userdata)getSession().getAttribute("gameUser");
		Member member1 = userDataService.findByMemberId(member.getId(),dict);
		member1.setClub(member.getClub());
		Userdata userData1 = userDataService.findById(userData.getUserid());
		getSession().setAttribute("member", member1);
		getSession().setAttribute("gameUser", userData1);
		return "client/transfer-apply";
	}
	
	/**
	 * 转账
	 * @param type
	 * @param outMoney
	 * @return
	 */
	@RequestMapping(value = "/transferApply")
	public @ResponseBody Result transferApply(int type,int outMoney){
		Result result = new Result();
		log.info("进入转账提交页面。。。"+outMoney);
		int num = 0;
		try {
		Member member = (Member)getSession().getAttribute("member");
		Userdata userData = (Userdata)getSession().getAttribute("gameUser");
		if(member!=null&&userData!=null){
			switch (type) {
			case 1://转入跑得快
				int total = member.getScore()  + member.getRewardscore();
				if(total >= outMoney){
					num = userDataService.clubInPdk(member,userData,outMoney,dict);
				}
				break;
			case 2://跑得快转出
				if(userData.getDiamondnum()>=(outMoney*10)){
					num = userDataService.pdkOutClub(member,userData,outMoney,dict);
				}
				break;
			}
			if(num>0){
				result.setCode(Result.STATUS_OK);
				result.setMsg("转账成功");
			}else{
				result.setCode(Result.STATUS_FALSE);
				result.setMsg("转账失败");
			}
		}else{
			result.setCode(Result.STATUS_ERR);
			result.setMsg("当前页面已过期，请重新登录");
		}
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(Result.STATUS_ERR);
			result.setMsg("网络异常，请稍候再试！");
		}
		return result;
	}
	
	
	/**
	 * 验证手机验证码
	 * @param dictId
	 * @param tel
	 * @return
	 */
	@RequestMapping(value = "/checkTel")
	public @ResponseBody Result checkTel(Long dictId,String tel){
		
		Result result = new Result();
		log.info("验证手机号码是否正确。。。"+dictId);
		try {
		if(dictId!=null&&StringUtils.isNotBlank(tel)){
			dict = dictionaryService.findById(dictId);
			if(dict!=null){
				//切换数据库连接
				dict.setIp(dict.getIp());
				dict.setName(dict.getName());
				dict.setUserName(dict.getUserName());
				dict.setPassword(dict.getPassword());
				Member member = userDataService.findByTel(tel,dict);
				if(member!=null){
					member.setClub(dict.getContent());
					getSession().setAttribute("member", member);
					//绑定其他平台
					Userdata userData = (Userdata)getSession().getAttribute("gameUser");
					UserBind userBind =  userBindService.findByGameId(userData.getUserid());
					if(userBind==null){
						UserBind bind = new UserBind();
						bind.setPdkId(userData.getUserid());
						bind.setOtherId(member.getId());
						bind.setDictId(dictId);
						bind.setTel(tel);
						int num = userBindService.add(bind);
						if(num>0){
							//发送短信
							sendMessage(result,tel);
							result.setCode(Result.STATUS_TRUE);
							result.setMsg("验证码发送成功！");
						}else{
							result.setCode(Result.STATUS_FALSE);
							result.setMsg("绑定失败");
						}
					}else{
						if(!tel.equals(userBind.getTel())){
							result.setCode(Result.STATUS_FALSE);
							result.setMsg("当前跑得快帐号已绑定俱乐部");
						}else{
							sendMessage(result,tel);
						}
					}
				}else{
					result.setCode(Result.STATUS_FALSE);
					result.setMsg("手机号码未注册该俱乐部");
				}
			}else{
				result.setCode(Result.STATUS_FALSE);
				result.setMsg("当前俱乐部不存在");
			}
		}else{
			result.setCode(Result.STATUS_ERR);
			result.setMsg("数据异常");
		}
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(Result.STATUS_ERR);
			result.setMsg("网络异常");
		}
		return result ;
	}


	/**
	 * 发送短信
	 * @param result
	 */
	private void sendMessage(Result result,String tel) {
		int codeLength = 6;//验证码长度
		code = "";
		//生成验证码
		for (int i = 0; i < codeLength; i++) {  
			code += (int)(Math.floor(Math.random()*9)) ;
		}
		log.info("手机验证码====>"+code);
		String content = "验证码"+code+",1分钟内输入有效，请勿向任何人提供您收到的短信验证码";
		// 发送参数
		OpenApi.initialzeAccount(sOpenUrl, account, authkey, cgid, csid);
		// 状态及回复参数
		DataApi.initialzeAccount(sDataUrl, account, authkey);
		List<SendResultBean> listItem = OpenApi.sendOnce(tel, content, 0, 0, null);
		if(listItem != null&&listItem.size()>0){
			for(SendResultBean t:listItem){
				if(t.getResult() >= 1){
					System.out.println("发送成功: 消息编号<" + t.getMsgId() + "> 总数<" + t.getTotal() + "> 余额<" + t.getRemain() + ">");
					result.setCode(Result.STATUS_OK);
					result.setMsg("短信发送成功！");
				}else{
					result.setCode(Result.STATUS_ERR);
					result.setMsg("短信发送失败！");
				}
			}
		}
		//设置定时器
		createTime();
	}
	
	/**
	 * 验证手机验证码
	 */
	@RequestMapping(value = "/checkTelCode")
	public @ResponseBody Result checkTelCode(String telCode){
		Result result = new Result();
		log.info("验证手机验证码。。。"+telCode);
		if(StringUtils.isNotBlank(code)&&StringUtils.isNotBlank(telCode)){
			if(code.equals(telCode)){
				result.setCode(Result.STATUS_OK);
				result.setMsg("验证成功！");
				code="";
			}else{
				result.setCode(Result.STATUS_FALSE);
				result.setMsg("验证码输入错误！");
			}
		}else{
			result.setCode(Result.STATUS_ERR);
			result.setMsg("验证码过期或验证码不存在！");
		}
		return result;
	}
	
	/**
	 * 验证码定时器
	 */
	private void createTime(){
		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				code = "";
			}
		}, 60000);
	}
	
	
	/**
	 * 定时任务
	 */
	public static void showTimer() {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                
            }
        };
        //设置执行时间
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);//每天
        //定制每天的4:00:00执行，
        calendar.set(year, month, day, 4, 0, 00);
        Date date = calendar.getTime();
        Timer timer = new Timer();
        System.out.println(date);
//        int period = 2 * 1000;
        //每天的date时刻执行task，每隔2秒重复执行
//        timer.schedule(task, date, period);
        //每天的date时刻执行task, 仅执行一次
        timer.schedule(task, date);
    }
	
}